import {
	login,
	getConfig
} from '@/common/api.js'
// #ifdef H5
const wx = require('jweixin-module');
// #endif
// 解析URL参数

function getUrlParam(name) {
	let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
	// #ifdef H5
	let r = window.location.search.substr(1).match(reg)
	if (r != null) {
		return unescape(r[2])
	}
	return null
	//#endif
}

function wxShare(type, title, desc, image) {
	
	return new Promise((resolve, reject) => {
		let pages = getCurrentPages(); //当前页
		let url = location.href.split('#')[0]
		let currentPage = pages[pages.length - 1]; //上个页面
		//#ifdef H5
		let options = currentPage.__page__.options
		//#endif
		
		//#ifndef H5
		let options = currentPage.options
		//#endif
		
		
		let user_info = uni.getStorageSync('user_info')
		let link=''
		if(this.$route.path=='/pagesC/perfect_data/index'){
			link=uni.$u.config.baseURL +'/#'+this.$route.fullPath+'&userId=' + user_info.userId
		}else if(this.$route.path=='/pagesA/square_details/index'){
			if(this.$route.fullPath.indexOf('&key')>-1){
				let length=this.$route.fullPath.length
				let index=this.$route.fullPath.indexOf('&key')
				let canshu=this.$route.path.slice(index,length)
			let url=this.$route.fullPath.replace(canshu,key)
				link=uni.$u.config.baseURL +'/#'+url
			}else{
				link=uni.$u.config.baseURL +'/#'+this.$route.fullPath+'&key='+type
			}
		}else{
			link=uni.$u.config.baseURL +'/#'+this.$route.fullPath
		}
		//邀请
		let shareData = {
			title: '蔡阿姨的红娘馆',
			desc: '蔡阿姨的红娘馆给你分享了一个信息，看点击查看吧！',
			link: link,
			imgUrl: 'https://hl-1316403513.cos.ap-shanghai.myqcloud.com/static/401673515180_.pic.jpg'
		}
		let data = {
			params: {
				url: url
			}
		}
		getConfig(data, {
			custom: {
				auth: false,
				toast: false,
				catch: false
			}
		}).then((result) => {
			wx.config({
				debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
				appId: result.appid, // 必填，公众号的唯一标识，填自己的！
				timestamp: result.timestamp, // 必填，生成签名的时间戳，刚才接口拿到的数据
				nonceStr: result.nonceStr, // 必填，生成签名的随机串
				signature: result.signature, // 必填，签名，见附录1
				jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData']
				// result.jsApiList
			})
			wx.ready(function() {
				//分享给朋友
				if (wx.updateAppMessageShareData) {
					wx.updateAppMessageShareData({
						title: shareData.title,
						desc: shareData.desc,
						link: shareData.link,
						imgUrl: shareData.imgUrl,
						success: function(res) {
							// window.location.reload(); 
							resolve(res)
						},
						cancel: function(err) {
							reject(err)
						}
					});
					wx.updateTimelineShareData({
						title: shareData.title, // 分享标题
						desc: shareData.desc,
						link: shareData.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
						imgUrl: shareData.imgUrl, // 分享图标
						success: function(res) {
							// window.location.reload(); 
							// 设置成功
							resolve(res)
						},
						cancel: function(err) {
							reject(err)
						}
					})
				} else {
					// wx.onMenuShareAppMessage({...obj})
					wx.onMenuShareTimeline({
						title: shareData.title,
						desc: shareData.desc,
						link: shareData.link,
						imgUrl: shareData.imgUrl,
						success: function(res) {
							resolve(res)
						},
						cancel: function(err) {
							reject(err)
						}
					});
					wx.onMenuShareAppMessage({
						title: shareData.title,
						desc: shareData.desc,
						link: shareData.link,
						imgUrl: shareData.imgUrl,
						// type: 'link',
						// dataUrl: '',
						success: function(res) {
							resolve(res)
						},
						cancel: function(err) {
							reject(err)
						}
					});
				}

			});
		}).catch((err) => {
			
		})
	})
	
}
/**
 * 隐藏h5分享朋友和朋友圈
 */
function hideMenuItems() {

	// #ifdef H5
	const url = location.href.split('#')[0]

	let data = {
		params: {
			url: url
		}
	}
	getAddress(data).then((result) => {
		wx.config({
			debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
			appId: result.config.appId, // 必填，公众号的唯一标识，填自己的！
			timestamp: result.config.timestamp, // 必填，生成签名的时间戳，刚才接口拿到的数据
			nonceStr: result.config.nonceStr, // 必填，生成签名的随机串
			signature: result.config.signature, // 必填，签名，见附录1
			jsApiList: ['hideMenuItems']
		})
		wx.ready(function() {
			wx.hideMenuItems({
				menuList: ['menuItem:share:appMessage', 'menuItem:share:timeline',
					'menuItem:share:qq',
					'menuItem:share:QZone'
				] // 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮，所有menu项见附录3
			});
		});
	}).catch((err) => {

	})
	// #endif
}
/**
 * 用户登录检测
 */
function userLoginCheck(code) {
	return new Promise((resolve, reject) => {
		let data = {

			code: code,
		}

		uni.showLoading({
			title: '登录中',
			mask: true
		})
		login(data, {
			custom: {
				auth: false,
				toast: false,
				catch: false
			}
		}).then((result) => {
			uni.hideLoading()
			if (result) {
				uni.setStorageSync('access_token', result.token)
				let user_info = {
					headimgurl: result.headimgurl,
					nickname: result.nickname,
					phone: result.phone,
					state: result.state,
					superiorUid: result.superiorUid,
					userId: result.userId
				}
				uni.setStorageSync('user_info', user_info)
				resolve(user_info)
			}
		})
	})
}
/*
 * 获取路由参数并授权
 */
function getRouteCode() {
	let pages = getCurrentPages(); //当前页
	let before_url = ''
	if (pages.length > 1) {

		let beforePage = pages[pages.length - 3]; //上个页面

		let urlParams = ''
		let itemStr
		if(beforePage.options){
			for (let item in beforePage.options) {
				itemStr = item + '=' + beforePage.options[item] + '&'
				urlParams += itemStr
			}
			if (urlParams.substr(-1) === '&') {
				urlParams = urlParams.substr(0, urlParams.length - 1)
			}
			before_url = beforePage.route + '?' + urlParams
		}else{
			before_url = 'pages/index/index'
		}
		

	} else {
		before_url = 'pages/index/index'
	}
	let currentPage = pages[pages.length - 1]; //上个页面
	console.log('上个页面',currentPage)
	//#ifdef H5
	let options = currentPage.__page__.options
	//#endif

	//#ifndef H5
	let options = currentPage.options
	//#endif
	// let test = 'h5test/#/'
	let test = 'mobile/#/'
	// ?state=1 ${test}
	let urls = `${uni.$u.config.baseURL}/?currentPage=/${before_url}#/${currentPage.route}`
	let url = encodeURIComponent(urls)
	window.location.href =
		'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx60a9d731b7722525&redirect_uri=' + url +
		'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect'
}
export default {
	getUrlParam,
	userLoginCheck,
	getRouteCode,
	wxShare
}
